package cn.cachalot.oj.service.impl;

import cn.cachalot.oj.controller.param.RegisterParam;
import cn.cachalot.oj.controller.param.UpdateUserInfoParam;
import cn.cachalot.oj.controller.res.UserInfoRes;
import cn.cachalot.oj.controller.res.UserStatusRes;
import cn.cachalot.oj.entity.User;
import cn.cachalot.oj.mapper.ProblemMapper;
import cn.cachalot.oj.mapper.UserMapper;
import cn.cachalot.oj.service.UserService;
import cn.cachalot.oj.util.BaseContext;
import cn.cachalot.oj.util.R;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private ProblemMapper problemMapper;

    @Override
    public User login(String userName, String password) {
        if (userName == null || userName.equals("")) {
            return null;
        }
        return userMapper.getUserByUserName(userName);
    }

    @Override
    @Transactional
    public String register(RegisterParam registerParam) {
        if (registerParam == null) {
            return "缺少参数!";
        }
        String userName = registerParam.getUserName();
        String password = registerParam.getPassword();
        if (userName == null || userName.equals("") || password == null || password.equals("")) {
            return "缺少参数!";
        }
        User user = userMapper.getUserByUserName(userName);
        if (user != null) {
            return "该用户名已被注册!";
        }
        user = new User();
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        user.setUserName(userName);
        user.setId(IdWorker.getId());
        user.setLevel(0);
        user.setCreateTime(LocalDateTime.now());
        userMapper.insert(user);
        return "success";
    }

    @Override
    public List<UserInfoRes> getUserList(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> userList = userMapper.getUserList();
        List<UserInfoRes> resList = userList.stream().map(item -> {
            UserInfoRes userInfoRes = new UserInfoRes();
            BeanUtils.copyProperties(item, userInfoRes);
            return userInfoRes;
        }).collect(Collectors.toList());
        return resList;
    }

    @Override
    @Transactional
    public String updateUserInfo(UpdateUserInfoParam updateUserInfoParam) {
        Long currentId = BaseContext.getId();
        Integer currentLevel = BaseContext.getLevel();
        User user = userMapper.selectById(updateUserInfoParam.getId());
        if (user == null) {
            return "找不到该用户!";
        }
        if (!Objects.equals(currentId, user.getId())) {
            if (updateUserInfoParam.getPassword() != null) {
                return "不能修改别人的密码!";
            }
            if (updateUserInfoParam.getUserName() != null) {
                if (!updateUserInfoParam.getUserName().equals(user.getUserName())) {
                    return "不能修改别人的用户名!";
                }
            }
        }
        if (currentLevel == 0) {
            if (!Objects.equals(currentId, user.getId())) {
                return "权限不足!";
            }
            if (updateUserInfoParam.getLevel() == 1) {
                return "权限不足!";
            }
        } else {
            if (Objects.equals(currentId, user.getId()) && updateUserInfoParam.getLevel() == 0) {
                return "不能给自己降级!";
            }
        }
        if (updateUserInfoParam.getUserName() != null) {
            User temp = userMapper.getUserByUserName(updateUserInfoParam.getUserName());
            if (temp != null && !Objects.equals(temp.getId(), currentId)) {
                return "该用户名已被注册!";
            }
        }
        User newUser = new User();
        BeanUtils.copyProperties(updateUserInfoParam, newUser);
        userMapper.updateById(newUser);
        return "success";
    }

    @Override
    public R<UserStatusRes> getUserStatusByUserId(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return R.error("找不到用户!");
        }
        UserStatusRes userStatusRes = new UserStatusRes();
        BeanUtils.copyProperties(user, userStatusRes);
        Integer submitCount = problemMapper.getSubmitCountByUserId(userId);
        userStatusRes.setSubmitCount(submitCount);
        Integer resolvedCount = problemMapper.getResolvedCountByUserId(userId);
        userStatusRes.setResolvedCount(resolvedCount);
        return R.success("用户数据").data(userStatusRes);
    }

    @Override
    public String getUserNameById(Long userId) {
        return userMapper.getUserNameByUserId(userId);
    }
}











